package priv.utrix.micro.utils;

import lombok.experimental.UtilityClass;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import priv.utrix.micro.dto.SecurityUserDto;

/**
 * @author utrix
 * @date 2020/11/12
 */
@UtilityClass
public class SecurityUtil {

    /**
     * 获取当前登录用户，如果没有获取不到则返回null值
     *
     * @return priv.utrix.micro.dto.SecurityUserDto
     */
    public SecurityUserDto getUser() {
        Authentication authentication = getAuthentication();
        if (authentication == null) {
            return null;
        }
        return getUser(authentication);
    }

    private SecurityUserDto getUser(Authentication authentication) {
        Object principal = authentication.getPrincipal();
        if (principal instanceof SecurityUserDto) {
            return (SecurityUserDto) principal;
        }

        return null;
    }

    private Authentication getAuthentication() {
        return SecurityContextHolder.getContext().getAuthentication();
    }



}
